package com.hmall.search;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.service.SearchService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class ItemsBatchSave {

    @Autowired
    private SearchService searchService;

    private RestHighLevelClient client;

    /**
     * 创建es的对象
     */
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.37.128:9200")
        ));
    }

    /**
     * 关闭es
     */
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    @Test
    void saveItems() throws IOException {
        BulkRequest bulkRequest = null;
        for (int i = 1; i < 178; i++) {
            PageDTO<Item> result = searchService.getItems(i, 500);
            List<Item> items = result.getList();
            bulkRequest = new BulkRequest();
            for (Item item : items) {
                ItemDoc itemDoc = new ItemDoc(item);
                IndexRequest indexRequest = new IndexRequest("item").id(itemDoc.getId().toString());
                String jsonString = JSON.toJSONString(itemDoc);
                indexRequest.source(jsonString, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        }
    }
}
